package com.gitee.fastmybatis.spring.boot.autoconfigure.multi;

import org.springframework.util.ClassUtils;

import javax.sql.DataSource;

public class DataSourceBuilder {

    private static final String[] DATASOURCE_LIST = {
            "com.zaxxer.hikari.HikariDataSource",
            "com.alibaba.druid.pool.DruidDataSource"
    };

    private DataSourceProp datasource;

    public static DataSourceBuilder builder(DataSourceProp datasource) {
        DataSourceBuilder builder = new DataSourceBuilder();
        builder.datasource = datasource;
        return builder;
    }

    public DataSource build() {
        Class<? extends DataSource> type = datasource.getType();
        if (type != null) {
            DataSourceCreator sourceCreator = getDataCreator(type);
            return sourceCreator.create(datasource);
        }

        for (String dataSourceClass : DATASOURCE_LIST) {
            Class<?> cls = findClass(dataSourceClass);
            if (cls == null) {
                continue;
            }
            DataSourceCreator sourceCreator = getDataCreator(cls);
            return sourceCreator.create(datasource);
        }
        throw new IllegalStateException("找不到数据源");
    }

    private DataSourceCreator getDataCreator(Class<?> type) {
        String className = type.getName();
        switch (className) {
            case "com.zaxxer.hikari.HikariDataSource":
                return new HikariDataSourceCreator();
            case "com.alibaba.druid.pool.DruidDataSource":
                return new DruidDataSourceCreator();
            default: {
                throw new IllegalStateException("不支持的数据源:" + className);
            }
        }
    }

    private Class<?> findClass(String name) {
        try {
            return ClassUtils.forName(name, null);
        } catch (Exception e) {
            return null;
        }
    }
}
